//
//  PrefsViewController.swift
//  EggTimer
//
//  Created by Huan Di on 12/01/2018.
//  Copyright © 2018 DHuan. All rights reserved.
//

import Cocoa

class PrefsViewController: NSViewController {

    @IBOutlet weak var presetsPopup: NSPopUpButton!
    @IBOutlet weak var customSlider: NSSlider!
    @IBOutlet weak var customTextField: NSTextField!
    
    //model
    
    var preference = Preferences()
    
    func displaySliderValueText(){
        let newTime = customSlider.integerValue
        customTextField.stringValue = "闹钟时间为\(newTime)分钟"
    }
    
    private func setEnableAndHighlightSilder(_ on : Bool) {
        customSlider.isEnabled = on
        customSlider.isHighlighted = on
    }
    func reflexCurrentPreference(){
        let selectedTimeInMinutes = Int(preference.selectedTime) / 60
        
        presetsPopup.selectItem(withTitle: "Custom")
        customSlider.isEnabled = true
        
        for item in presetsPopup.itemArray {
            if item.tag == selectedTimeInMinutes {
                presetsPopup.select(item)
                setEnableAndHighlightSilder(false)
                break
            }
        }
        
        customSlider.integerValue = selectedTimeInMinutes
        displaySliderValueText()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do view setup here.
        reflexCurrentPreference()
    }
    
    func saveNewPreference() -> Void {
        preference.selectedTime = customSlider.doubleValue * 60
        NotificationCenter.default.post(name: Notification.Name(rawValue: "PreferenceChanged"), object: nil)
    }
    
    @IBAction func popupValueChanged(_ sender: NSPopUpButton) {
        if sender.selectedItem?.title == "Custom" {
            setEnableAndHighlightSilder(true)
            return
        }
        
        let newTime = sender.selectedTag()
        customSlider.integerValue = newTime
        displaySliderValueText()
        setEnableAndHighlightSilder(false)
    }
    @IBAction func sliderValueChanged(_ sender: NSSlider) {
        displaySliderValueText()
    }
    @IBAction func cancelButtonClicked(_ sender: NSButton) {
        view.window?.close()
    }
    @IBAction func okButtonClicked(_ sender: NSButton) {
        saveNewPreference()
        view.window?.close()
    }

    
}
